package org.zn.note.java8;

import java.util.Optional;

/**
 * 用 Optional 取代 null
 * {@link Optional}
 */
public class Ch10_Optional {

    public static void main(String[] args) {

    }

    private String getCarInsuranceName1(Person person) {
        // car - insurance - name 全是null
        return person.getCar().getInsurance().getName();
    }

    // 判NULL方式一：深层质疑
    private String getCarInsuranceName2(Person person) {
        if (person != null) {
            Car car = person.getCar();
            if (car != null) {
                Insurance insurance = car.getInsurance();
                if (insurance != null) {
                    return insurance.getName();
                }
            }
        }
        return "Unknown";
    }

    // 判NULL方式二：过多的退出语句
    private String getCarInsuranceName3(Person person) {
        if (person == null) {
            return "Unknown";
        }
        Car car = person.getCar();
        if (car == null) {
            return "Unknown";
        }
        Insurance insurance = car.getInsurance();
        if (insurance == null) {
            return "Unknown";
        }
        return insurance.getName();
    }

    private static class Person {
        private Car car;

        public Car getCar() {
            return car;
        }
    }

    private static class Car {
        private Insurance insurance; // 保险

        public Insurance getInsurance() {
            return insurance;
        }
    }

    private static class Insurance {
        private String name;

        public String getName() {
            return name;
        }
    }

    // 用Optional重写Person、Car、Insurance
    private static class Person2 {
        private Optional<Car2> car;

        public Optional<Car2> getCar() {
            return car;
        }
    }

    private static class Car2 {
        private Optional<Insurance2> insurance;

        public Optional<Insurance2> getInsurance() {
            return insurance;
        }
    }

    private static class Insurance2 {
        private String name;

        public String getName() {
            return name;
        }
    }
}
